/**
 * Created by bian on 16-3-9.
 */
/* css */
require('../admin-base/common.js');
require('fex-webuploader/dist/webuploader.css');
require('../../css/lib/webuploader.scss');
require('../../css/img-upload-thumbnail.scss');

/* js */
var $ = jQuery;
var WebUploader = require('fex-webuploader');
require('imports?$=jquery!jquery-validation');


require('angular');


$(function() {
   var app = angular.module('app', []);

    var uploader = new WebUploader.Uploader({
        swf: '/dist/Uploader.swf',
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        },
        pick: {
            id: '#upload-picker',
            multiple: true
        },
        fileSizeLimit: 1024 * 1024 * 3,
        fileNumLimit: 10,
        server: '/upload'
    });

    var uploaded = false;
    var $form = $('#form_sample_1');

   app.controller('formCtrl',['$scope','$http',function(scope,$http){
       var shopId = location.href.substr(-1);
       if(isNaN(parseInt(shopId))){
           scope.actionUrl = '/adminer/shop-info';
       }else{
           scope.actionUrl = '/adminer/shop-info/' + shopId;
       }
       scope.imgs = [];

       scope.mainImg = 0;
       scope.mainImgUrl = '';
       scope.imgsUrl = [];
       scope.data = [];

       scope.setMain = function (index) {
           scope.mainImg = index;
       };

       scope.remove = function (index) {
           scope.data.splice(index, 1);
           scope.imgs.splice(index, 1);
       };

       scope.init = function () {
           var imgDom = angular.element('#imgs');
           try {
               if (imgDom.data('main')) {
                   scope.data = [imgDom.data('main')].concat(JSON.parse(imgDom.html()));
               } else {
                   scope.data = [];
               }
           } catch (e){
               scope.data = [imgDom.data('main')];
           }

           scope.imgs = scope.data.slice();

           scope.mainImgUrl = scope.data[scope.mainImg];
       };

       scope.init();

       uploader.on('fileQueued', function (file) {
           uploader.makeThumb( file, function( error, ret ) {
               if ( error ) {
                   alert('预览失败，请刷新重试');
               } else {
                   scope.imgs.push(ret);
                   scope.data.push(file);
                   scope.$apply();
               }
           }, 640, 260);
       });

       uploader.on('uploadSuccess', function (file, ret) {
           for(var i in scope.data) {
               var ele = scope.data[i];
               //debugger
               if (ele.id && ele.id == file.id) {
                   scope.data[i] =  ret.file_path;
                   break;
               }
           }
       });

       uploader.on('uploadFinished', function () {
           for(var i in scope.data) {
               var filePath = scope.data[i];
               if (i == 0) {
                   scope.mainImgUrl = filePath;
               } else{
                   scope.imgsUrl.push(filePath);
               }
           }
           //scope.mainImgUrl = scope.imgsUrl[scope.mainImg];
           scope.$apply();
           $form[0].submit();
       });




       $form.validate({
           errorElement: 'span', //default input error message container
           errorClass: 'help-block', // default input error message class
           focusInvalid: false, // do not focus the last invalid input
           ignore: "",
           rules: {
               shopName: {
                   required: true
               },
               phone:{
                   required: true,
                   maxlength:11,
                   minlength:11
               },
               TopAreaId:{
                   required:true
               },
               areaId:{
                   required:true
               }
           },

           messages: {
               shopName: {
                   required: '请填写商店名'
               },
               phone:{
                   required: '请填写手机号',
                   maxlength:'请输入正确手机号',
                   minlength:'请输入正确手机号'
               },
               TopAreaId:{
                   required:'请选择商店所属区域'
               },
               areaId:{
                   required:'请选择商店所属区域'
               }
           },

           invalidHandler: function (event, validator) {
           },

           highlight: function (element) {
               $(element)
                   .closest('.form-group').addClass('has-error');
           },

           unhighlight: function (element) {
               $(element)
                   .closest('.form-group').removeClass('has-error'); // set error class to the control group
           },

           success: function (label) {
               label
                   .closest('.form-group').removeClass('has-error'); // set success class to the control group
           },

           submitHandler: function (form) {
               if (uploaded) {
                   form.submit();
               }
               uploaded = true;
               uploader.upload();
           }
       });
   }]);

    app.controller('AreaCtrl',['$scope','$http',function(scope,$http){
        scope.init = function(){
            var $this = this;
            var defaultTopAreaId = angular.element('#defaultTopArea').html();
            var defaultAreaId = angular.element('#defaultArea').html();
            $http
                .get('/adminer/area/all')
                .success(function(data){
                    $this.TopAreas = data;
                    $this.selectedTopArea = defaultTopAreaId;
                    $this.selectedArea = defaultAreaId;
                });
        };

        scope.init();

        scope.$watch('selectedTopArea',function (newValue,oldValue){
            var AreaArr = scope.TopAreas;
            for(var x in AreaArr){
                if(AreaArr[x].id == newValue){
                    scope.areas = AreaArr[x].Areas.concat();
                }
            }
        })
    }]);

   angular.bootstrap(document.documentElement, ['app']);
});